const http = require('http');
const querystring = require('querystring');

const server = http.createServer((req,res) => {
  const method = req.method;
  const url = req.url;
  const path = url.split('?')[0];
  const query = querystring.parse(url.split('?')[1]);

  //设置返回格式为json
  res.setHeader('content-type','application/json')

  const resData = {
    method,
    url,
    path,
    query
  }
  // res.writeHead(200,{'content-type':'application/json'})//向请求发送响应头

  //返回
  if(method === 'GET'){
    res.end(JSON.stringify(resData))
  }

  if(method==='POST'){
    let postData='';
    req.on('data',chunk=>{
      postData+=chunk.toString()
    })

    req.on('end',() => {
      resData.postData = postData
      res.end(JSON.stringify(resData))
    })
  }
  
})

// http://localhost:4000/user?name=wang&id=1

server.listen(4000,()=>{
  console.log('listening on 4000 port')
})



